package com.tanhua.appserver.interceptor;

import com.tanhua.model.pojo.User;
import com.tanhua.utils.JwtUilt;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: JW
 * @Description: TODO 全局拦截器
 * @DateTime: 2021/12/21 20:54
 **/

public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //在请求头中拿到token
        String token = request.getHeader("Authorization");

        //判断token
        if(!JwtUilt.verifyToken(token)){

            response.setStatus(401);
            return false;
        }

        //token通过时 需要将token解析
        Claims claims = JwtUilt.getClaims(token);
        Long id = Long.parseLong(claims.get("id").toString());
        String phone = (String) claims.get("phone");

        //组装用户数据
        User user = new User();
        user.setId(id);
        user.setMobile(phone);

        //需要将该用户信息存入到ThreadLocal
        UserHolder.set(user);

        //最后放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //将该线程空间清空
        UserHolder.remove();
    }
}
